package com.kiln.juxingqs.ui.socket;

import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.kiln.juxingqs.R;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketIOActivity extends AppCompatActivity {

    //创建Socket对象
    private Socket mSocket;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_websocket);
        setListener();

    }

    private void setListener() {
        TextView tvLj = findViewById(R.id.tv_lj);
        TextView tvContent = findViewById(R.id.tv_content);

        try {
            //初始化mSocket
//            IO.Options opts = new IO.Options();
            mSocket = IO.socket("http://192.168.0.66:5000/test");
            //链接成功回调监听
            mSocket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    runOnUiThread(() -> {
                        tvLj.setText("链接成功");
                    });
                    mSocket.emit("message", "hi");
//                    mSocket.disconnect();
                }

                //消息接收回调监听
            }).on("server_response", new Emitter.Listener() {
                //message is the keyword for communication exchanges
                @Override
                public void call(Object... args) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvContent.setText(args[0].toString());
                        }
                    });
                    mSocket.emit("message", args[0].toString());
                }

            }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

                @Override
                public void call(Object... args) {
//                    mSocket.emit("disconnect", args.toString());
                }
            });
            //开始连接
            mSocket.connect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //消息发送
            mSocket.emit("text", "终于发过去了");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSocket.off();
        mSocket.disconnect();
    }
}
